package com.tuomaxu.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class StaticResourceUtil {

    public static void outputStaticResource(File file, OutputStream outputStream) throws IOException {
        InputStream inputStream = new FileInputStream(file);
        int count = 0;
        while(count == 0) {
            count = inputStream.available();
        }

        String httpHeader200 = HttpProtocolUtil.getHttpHeader200(count);

        outputStream.write(httpHeader200.getBytes(StandardCharsets.UTF_8));

        //需要读取的文件总大小，但文件可能较大，不能一次读取，需要多次读取
        int resourceSize = count;
        //当前已经读取文件的大小
        int readSize = 0;
        //每次读取文件的大小
        int bufferSize = 1024;
        //是否继续读取
        boolean reading = true;
        //但要判断最后一次，如果最后一次不满足1024个字节，就会读出很多空字符或未知内容
        while (reading){
            int unReadSize = resourceSize - readSize;
            if(unReadSize < bufferSize) {
                //如果未读内容小于缓冲区大小，说明这一次就能读完
                reading = false;
                byte[] bytes = new byte[unReadSize];
                inputStream.read(bytes);
                outputStream.write(bytes);
            }else {
                byte[] bytes = new byte[bufferSize];
                inputStream.read(bytes);
                outputStream.write(bytes);
                readSize += bufferSize;
            }
        }

    }
}
